package com.laijiale.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.laijiale.dto.CoursePageDTO;
import com.laijiale.entity.Course;
import com.laijiale.es.CourseDoc;
import com.laijiale.service.CourseService;
import com.laijiale.vo.CoursePageVO;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * @author laijiale
 * @date 2025年01月08日 16:47
 */
@CacheConfig(cacheNames = "course")
@Service
public class CourserServiceImpl implements CourseService {

    @Cacheable(key = "#root.methodName + ':' + #p0.toString()",
            condition = "#p0 !=null",
            unless = "#result == null "
    )
    @Override
    public CoursePageVO<CourseDoc> search(CoursePageDTO dto) {
        //1.取值
        int pageNumber=dto.getPageNum();
        int pageSize=dto.getPageSize();
        String keyword=dto.getKeyword();

        //2.设置默认值
        pageNumber= ObjectUtil.isNotNull(pageNumber) ? pageNumber : 0;
        pageSize= ObjectUtil.isNotNull(pageSize) ? pageSize : 10;

        //3.参数处理:对pageNum进行最小边界保护，规避ES报错，注意ES的分页是从0开始的
        pageNumber=pageNumber-1;
        if(pageNumber < 0 ) pageNumber=0;
        if(pageSize < 0 ) pageSize=0;

        //4.构建查询条件
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (StrUtil.isNotEmpty(keyword)) {
            MatchQueryBuilder titleQuery = QueryBuilders.matchQuery("title", keyword);
            MatchQueryBuilder authorQuery = QueryBuilders.matchQuery("author", keyword);
            boolQueryBuilder.should(titleQuery).should(authorQuery);
        }

        // 执行搜索
        List<CourseDOC> searchResults = myEs.search(boolQueryBuilder, CourseDOC.class, pageNumber, pageSize);

        // 计算总记录数和总页数
        long totalRow = myEs.count(boolQueryBuilder, CourseDOC.class);
        int totalPage = (int) Math.ceil((double) totalRow / pageSize);

        //4.组装VO并返回
        CoursePageVO<CourseDOC> result=new CoursePageVO<>();
        result.setPageNum(pageNumber+1);
        result.setPageSize(pageSize);
        result.setTotalRow(totalRow);
        result.setTotalPage(totalPage);
        result.setRecords(searchResults);
        return result;
    }
}

